$(function () {

    if (localStorage.getItem('goumai')) {
        //本地存储的数据
        var goumaiArr = JSON.parse(localStorage.getItem('goumai'))

        $.ajax({
            url: '../data/data4.json',
            type: 'get',
            datatype: 'json',
            success: function (data) {
                var strDom4 = ''
                $.each(data, function (index, item) {

                    $.each(goumaiArr, function (ind, obj) {
                        if (item.id === obj.id) {
                            console.log(1)
                            var goods = `                  
    <div class="gl-list clearfix">
        <label class="checkbox">
            <input type="checkbox" class="xuan" checked="checked" readonly="readonly" data-id="${obj.id}" data-num="${obj.num}">
        </label>
        <div class="gl-list-area">
            <a href="http://localhost:3001/look.html">
                <img src="${item.imgurl}" alt="">
            </a>

            <ul class="clearfix">
                <li>
                    <a title="HUAWEI P40 Pro+ 5G 全网通 8GB+256GB（陶瓷白）" class="p-name">
                        
                    ${item.name}
                    </a>
                    <p class="p-info">${item.info}</p>
                </li>
                <li class="p-single-price">
                    <div class="p-price">
                        ￥&nbsp;<span>${item.price}</span>
                    </div>
                </li>
                <li class="stock">
                    <div class="p-stock">
                        <div class="p-stock-area">
                            <input type="text" class="p-stock-text" value="${obj.num}">
                        
                        <p class="p-stock-btn" data-id="${item.id}" data-num=""${obj.num}>
                            <button class="jian">-</button>
                            <button class="jia">+</button>
                        </p>
                    </div>
                    </div>
                </li>
                <li class="p-price-total">
                    <div>
                        &nbsp;￥<span>${item.price}</span> 
                    </div>
                </li>
                <li class="shanchu" >
                    <a class="p-del" data-id="${item.id}" data-num="${obj.num}">
                        删除
                    </a>
                </li>         
            </ul>
        </div>
        
    </div>
            
`
                            strDom4 += goods
                        }
                    })
                })
                $('.add').html(strDom4)
            }
        })
    } else {

        var liDom = `
      <div class="gl-list" style="height:400px;padding-top:100px;text-align:center">
      <span class="kongpic"></span>
      <p class="kong">您的购物车里什么也没有哦~</p>
      <a href="http://localhost:3001/index2.html" class="empty">
      去逛逛
      </a>
      </div>
      `
        $('.add').html(liDom)
    }
    setTimeout(function () {
        var todolist = {
            init: function () {
                this.catchElement()
                this.bindEvent()
                this.total()
            },
            catchElement: function () {
                this.goodsList = document.querySelector('.goodsList')
                this.btn = document.querySelector('.p-stock-btn')
                this.quan = $('.quan')
                this.list = $('.shanchu')
                this.checkbox = $('.checkbox')
                this.priceTotal = $('.p-price-total')
                this.quan1 = $('.quan1')
            },
            bindEvent: function () {
                var that = this
                if (localStorage.getItem('name')) {
                    var nameArr = JSON.parse(localStorage.getItem('name'))
                } else {
                    var nameArr = []
                }
                //登陆后渲染用户信息
                $.each(nameArr, function (index, item) {
                    $('.dl').html(item.name)
                    $('.zc').html('')
                    $('.login-prompt').remove()

                })

                //记录当前url
                $('.dl').on('click', function () {
                    var urlArr = []
                    var url1 = window.location.href
                    console.log(url1)
                    urlArr.push({ 'url': url1 })
                    localStorage.setItem('url', JSON.stringify(urlArr))
                })
                $('.deng').on('click', function () {
                    var urlArr = []
                    var url1 = window.location.href
                    console.log(url1)
                    urlArr.push({ 'url': url1 })
                    localStorage.setItem('url', JSON.stringify(urlArr))
                })
                //被删除的商品放在购物车下方，用户可以重新点击进行购买

                //全选选中时，单选框选中
                this.quan.click(function () {
                    if ($(this).prop('checked')) {
                        $('.xuan').prop('checked', true)
                        that.quan1.prop('checked', true)

                    } else {
                        $('.xuan').prop('checked', false)
                        that.quan1.prop('checked', false)
                    }

                    that.total()
                })
                this.quan1.click(function () {
                    if ($(this).prop('checked')) {
                        $('.xuan').prop('checked', true)
                        that.quan.prop('checked', true)

                    } else {
                        $('.xuan').prop('checked', false)
                        that.quan.prop('checked', false)
                    }

                    that.total()
                })
                this.checkbox.on('click', '.xuan', function () {
                    //判断是否全部选中
                    $('.xuan').each(function (index, dom) {
                        if (!$(dom).prop('checked')) {
                            that.quan.prop('checked', false)
                            that.quan1.prop('checked', false)
                            return false
                        } else {
                            that.quan.prop('checked', true)
                            that.quan1.prop('checked', true)
                        }

                    })
                    that.total()
                })

        //删除购物车数据
        this.list.on('click', '.p-del', function () {
            //获取要删除的商品
            var id = $(this).attr('data-id')
            var num = $(this).attr('data-num')
            $(this).closest('.gl-list').remove()
            that.rebuy(id, num)
            $('.xuan').each(function (index, dom) {
                if (!$(dom).prop('checked')) {
                    that.quan.prop('checked', false)
                    that.quan1.prop('checked', false)
                    return false
                }
                that.quan.prop('checked', true)
                that.quan1.prop('checked', true)
            })
            //遍历
            $.each(goumaiArr, function (index, item) {
                if (item.id === id) {

                    goumaiArr.splice(index, 1)

                    return false
                }
            })
            if (goumaiArr.length > 0) {
                localStorage.setItem('goumai', JSON.stringify(goumaiArr))
            } else {
                localStorage.removeItem('goumai')
                that.quan.prop('checked', false)
                that.quan1.prop('checked', false)
                var liDom = `
            <div class="gl-list" style="height:400px;padding-top:100px;text-align:center">
            <span class="kongpic"></span>
            <p class="kong">您的购物车里什么也没有哦~</p>
            <a href="http://localhost:3001/index2.html" class="empty">
            去逛逛
            </a>
            </div>
            `
                $('.add').html(liDom)
            }
            that.total()
        })
        //删除被勾选的商品
        $('.total-contorl').on('click', 'a', function () {
            $('.xuan').each(function (index, dom) {
                var id = $(this).attr('data-id')
                var num = $(this).attr('data-num')
                that.rebuy(id, num)
                if ($(dom).prop('checked')) {
                    $(dom).closest('.gl-list').remove()
                    //遍历
                    $.each(goumaiArr, function (index, item) {
                        if (item.id === id) {
                            //截取
                            goumaiArr.splice(index, 1)
                            return false
                        }
                    })
                    if (goumaiArr.length > 0) {
                        //保存
                        localStorage.setItem('goumai', JSON.stringify(goumaiArr))
                    } else {
                        //如果购物车为空则显示购物车为空提示
                        localStorage.removeItem('goumai')
                        that.quan.prop('checked', false)
                        that.quan1.prop('checked', false)
                        var liDom = `
            <div class="gl-list" style="height:400px;padding-top:100px;text-align:center">
            <span class="kongpic"></span>
            <p class="kong">您的购物车里什么也没有哦~</p>
            <a href="http://localhost:3001/index2.html" class="empty">
            去逛逛
            </a>
            </div>
            `
                        $('.add').html(liDom)
                    }
                }

            })
            that.total()
        })
        //为加法按钮添加事件
        $('.p-stock-btn').on('click', '.jia', function () {

            var _this = this
            var num = $(this).parent().attr('data-num')
            var id = $(this).parent().attr('data-id')
            $.each(goumaiArr, function (index, item) {
                if (item.id === id) {
                    item.num++
                    num = item.num
                    $(_this).parent().parent().children('input').attr("value", item.num)
                    var price = $(_this).parent().parent().parent().parent().siblings('.p-single-price').children('.p-price').children('span').html()

                    //获取小计
                    var e = price * num

                    $(_this).parent().parent().parent().parent().siblings('.p-price-total').children('div').children('span').html(e.toFixed(2))
                    that.total()
                }
            })

            localStorage.setItem('goumai', JSON.stringify(goumaiArr))

        })
        //为减法按钮添加事件
        $('.p-stock-btn').on('click', '.jian', function () {

            var _this = this
            var num = $(this).parent().attr('data-num')
            var id = $(this).parent().attr('data-id')
            $.each(goumaiArr, function (index, item) {
                if (item.id === id && item.num != 1) {
                    item.num--
                    num = item.num
                    $(_this).parent().parent().children('input').attr("value", item.num)

                    var price = $(_this).parent().parent().parent().parent().siblings('.p-single-price').children('.p-price').children('span').html()

                    //获取小计
                    var e = price * num

                    $(_this).parent().parent().parent().parent().siblings('.p-price-total').children('div').children('span').html(e.toFixed(2))
                    that.total()
                }

            })

            localStorage.setItem('goumai', JSON.stringify(goumaiArr))

        })
        //当用户还未登录时跳转到登陆页面
        if (localStorage.getItem('name')) {

            var nameArr = JSON.parse(localStorage.getItem('name'))
        } else {
            var nameArr = []
        }
        console.log(nameArr)
        $('.total-btn').on('click', function () {
            //判断是否已经登陆
            if (localStorage.getItem('name')) {
                alert("支付成功！")
            } else {
                var urlArr = []
                var url1 = window.location.href

                urlArr.push({ 'url': url1 })
                localStorage.setItem('url', JSON.stringify(urlArr))
                window.location.href = "http://localhost:3001/login.html"
            }
        })
    },
    total: function () {
        var num1 = 0
        var num2 = 0
        //遍历所有单选框
        $('.xuan').each(function (ind, dom) {
            //找出被选中的商品
            if ($(dom).prop('checked')) {
                var mm = $(dom).closest('.gl-list').children('.gl-list-area').children('ul')
                    .children('.stock').children('.p-stock')
                    .children('.p-stock-area').children('.p-stock-text').val()
                //累加
                num1 += parseInt(mm)
                //获取被选中商品的价格
                var nn = $(dom).closest('.gl-list').children('.gl-list-area').children('ul')
                    .children('.p-price-total').children('div').children("span").html()

                //进行累加
                num2 += parseInt(nn)
            }
        })
        //将数量、金额追加到合适的地方
        $('.total-choose').children('em').html(num1)
        $('.total-price').children('p').children("span")
            .children("i").html(num2.toFixed(2))
    },
    rebuy: function (id, num) {
        if (localStorage.getItem('layout')) {
            var layoutArr = JSON.parse(localStorage.getItem('layout'))
        } else {
            var layoutArr = []
        }
        layoutArr.push({ 'layout': id, "num": num })
        localStorage.setItem('layout', JSON.stringify(layoutArr))
        $.ajax({
            url: '../data/data4.json',
            type: 'get',
            datatype: 'json',
            success: function (data) {
                var strDom5 = ''
                $.each(data, function (index, item) {
                    console.log(layoutArr[layoutArr.length - 1].layout)
                    if (item.id === layoutArr[layoutArr.length - 1].layout) {
                        var xinxi = `
                            <div class="h">
                            <h2>已删除商品</h2>
                        </div>
                        <ul class="clearfix">
                            <li>商品</li>
                            <li>数量</li>
                            <li>金额</li>
                            <li>操作</li>
                        </ul>
                        <ul class="clearfix">
                            <li><a href="">  ${item.name}</a></li>
                            <li>x${layoutArr[layoutArr.length - 1].num}</li>
                            <li>${item.price}</li>
                            <li>
                                <a class="pro-delete-btn">重新购买</a>
                            </li>
                        </ul>
                                        `
                                    strDom5 = xinxi
                                }
                            })
                            $('.pro-delete').html(strDom5)
                        }
                    })
                }
            }

            //调用init函数
            todolist.init()
        }, 100)


    })